package com.jfinal_demo.app.services;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;

import java.util.List;

public class BaseService {
    protected <T extends Model<T>> Page<T> page(T model, String countSql, String listSql, Kv kv, int pageNumber, int pageSize) {
        int count = count(countSql, kv);
        if (count == 0) return new Page<>();

        if (pageNumber <= 0) pageNumber = 1;
        if (pageSize <= 0) pageSize = 20;
        int offset = (pageNumber - 1) * pageSize;
        kv.set("offset", offset).set("limit", pageSize);

        SqlPara sqlPara = Db.getSqlPara(listSql, kv);
        List<T> list = model.find(sqlPara);
        return new Page<>(list, pageNumber, pageSize, (count + pageSize - 1) / pageSize, count);
    }

    protected int count(String countSql, Kv kv) {
        SqlPara sqlPara = Db.getSqlPara(countSql, kv);
        return Db.queryInt(sqlPara.getSql(), sqlPara.getPara());
    }
}
